﻿Imports System.IO
Imports Ionic.Zip

Public Class IdmlFile
	Public Property Stories As List(Of Stories.Story)

	Private Property Spreads As List(Of Spreads.Spread)

	Public Sub Open(path As String)
		Dim tempExtractionPath As String

		tempExtractionPath = ExtractZip(path)
		LoadData(tempExtractionPath)
		DeleteExtractionFolder(tempExtractionPath)
	End Sub

	Public Sub Save(path As String)
		Throw New NotImplementedException
	End Sub

	Private Function ExtractZip(filePath As String) As String
		Dim TempPath As String
		Dim TargetDir As String

		TempPath = System.Environment.GetEnvironmentVariable("tmp", EnvironmentVariableTarget.User)
		TargetDir = Path.Combine(TempPath, Path.GetRandomFileName())

		Debug.WriteLine("Extracting file: {0} to temporary extract path: {1}", filePath, TargetDir)

		Using zip1 As ZipFile = ZipFile.Read(filePath)
			For Each e As ZipEntry In zip1
				e.Extract(TargetDir, ExtractExistingFileAction.OverwriteSilently)
			Next
		End Using

		Return TargetDir
	End Function

	Private Sub LoadData(tempExtractionPath As String)

		' Read which stories exist via designmap.xml

		' Quick & dirty way for now
		Dim StoryFiles() As String
		If Directory.Exists(Path.Combine(tempExtractionPath, "Stories")) Then
			StoryFiles = Directory.GetFiles(Path.Combine(tempExtractionPath, "Stories"))

			Dim sl As New StoryLoader()
			Me.Stories = sl.LoadStories(StoryFiles)
		End If

		' Read which spreads exist via designmap.xml
		Dim SpreadFiles() As String
		If Directory.Exists(Path.Combine(tempExtractionPath, "Spreads")) Then
			SpreadFiles = Directory.GetFiles(Path.Combine(tempExtractionPath, "Spreads"))

			Dim spl As New SpreadLoader()
			Me.Spreads = spl.LoadSpreads(SpreadFiles)
		End If
	End Sub

	Private Sub DeleteExtractionFolder(tempExtractionPath As String)
		If Directory.Exists(tempExtractionPath) Then
			Directory.Delete(tempExtractionPath, True)
		End If
	End Sub

End Class